<?php

namespace app\admin\model;

use app\admin\model\ProfitShareLog;
use think\Model;
use EasyWeChat\Factory;

class Order extends Model
{
    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];


    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3'), '4' => __('Status 4')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function fangjian()
    {
        return $this->belongsTo('Fangjian', 'fangjian_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    //未支付订单状态修改为已支付
    public static function updateOrderStatusToPayed($order_id, $order_status, $quan_id, $quan_price, $real_price, $pay_type = 0)
    {
        $order = self::where('id', $order_id)->find();
        $order->pay_type = $pay_type;
        $order->status = $order_status;
        $order->quan_id = $quan_id;
        $order->quan_price = $quan_price;
        $order->real_price = $real_price;
        $order->settlement_money = $real_price;
        $order->save();
    }


    //续费旧订单,如果这个订单是一个续费订单的情况
    public static function xufeiOrder($order_id)
    {
        //类型 x_status=1 续费订单 =0 正常订单
        $order = self::where('id', $order_id)->where('x_status', 1)->find();
        if (!$order) {
            return false;
        }
        $x_id = $order->x_id;
        if ($x_id <= 0) {
            return false;
        }
        //找到旧订单
        $old_order = self::where('id', $x_id)->find();
        $old_order->fuwu_sc = $old_order->fuwu_sc + $order->fuwu_sc;
        $old_order->quan_price = $old_order->quan_price + $order->quan_price;
        $old_order->real_price = $old_order->real_price + $order->real_price;
        $old_order->price = $old_order->price + $order->price;
        $old_order->save();
        return true;
    }

    // 分账
    public static function profitSharing($order_id, $add_user_id = 0)
    {
        $order_info = self::where('id', $order_id)->find();
        if (!$order_info) return ['code' => 0, 'msg' => '订单信息不存在'];
        if ($order_info['status'] != 3) return ['code' => 0, 'msg' => '订单状态不符合分账条件'];

        // 分账记录
        $profit_share_log = ProfitShareLog::where('system_order_id', $order_id)->where('status', 1)->find();
        if ($profit_share_log) return ['code' => 0, 'msg' => '该笔订单已分账，请勿重复操作'];

        // 房间信息
        $fangjian_info = Fangjian::where('id', $order_info['fangjian_id'])->find();
        if (!$fangjian_info) return ['code' => 0, 'msg' => '房间信息不存在'];

        // 门店信息
        $category_info = Category::where('id', $fangjian_info['category_id'])->find();
        if (!$category_info) return ['code' => 0, 'msg' => '门店信息不存在'];

        // 分账金额（元）
        $amount = $order_info['real_price'] * $category_info['profit_share_rate'] / 100;
        if (!$amount) return ['code' => 0, 'msg' => '分账金额为0'];

        if ($category_info['profit_share_type'] == 1 && !$category_info['profit_share_merchant_id']) return ['code' => 0, 'msg' => '未设置接收分账商户号'];

        if ($category_info['profit_share_type'] == 2) {
            if (!$category_info['profit_share_user_id']) return ['code' => 0, 'msg' => '未设置接收分账人'];

            $user_info = User::where('id', $category_info['profit_share_user_id'])->find();
            if (!$user_info || !$user_info['openid']) return ['code' => 0, 'msg' => '接收分账人用户openid不存在'];
        }

        $out_order_no = $order_id . "_" . time();
        $profit_share_log = ProfitShareLog::create([
            'add_user_id' => $add_user_id,
            'system_order_id' => $order_id,
            'order_id' => '', // 微信分账单号，微信支付系统返回的唯一标识
            'transaction_id' => $order_info['transaction_id'],
            'out_order_no' => $out_order_no,
            'description' => '分账',
            'amount' => $amount,
            'rate' => $category_info['profit_share_rate'],
            'type' => $category_info['profit_share_type'],
            'merchant_id' => $category_info['profit_share_merchant_id'],
            'user_id' => $category_info['profit_share_user_id'],
            'openid' => !empty($user_info['openid']) ? $user_info['openid'] : '',
            'category_id' => $category_info['id'],
            'status' => 0,
        ]);

        $wechat_config = \addons\epay\library\Service::getConfig('wechat');

        $config = [
            'app_id'     => config('site.appid'),
            "secret"     => config('site.appsecret'),
            'mch_id'     => $wechat_config['mch_id'],
            'key'        => $wechat_config['key'],
            'cert_path'  => $wechat_config['cert_client'],
            'key_path'   => $wechat_config['cert_key'],
            'notify_url' => url('api/dylogic/profitSharingNotify', ['uniacid' => config('site.uniacid')], true, true),
        ];
        $payment = Factory::payment($config);
        $receivers = [
            [
                "type"        => $category_info['profit_share_type']==1 ? "MERCHANT_ID" : "PERSONAL_OPENID",
                "account"     => $category_info['profit_share_type']==1 ? $profit_share_log['merchant_id'] : $profit_share_log['openid'],
                "amount"      => $amount*100,
                "description" => $category_info['profit_share_type']==1 ? "分到商户" : "分到个人"
            ],
        ];
        $res = $payment->profit_sharing->share($profit_share_log['transaction_id'], $profit_share_log['out_order_no'], $receivers);
        if(empty($res['order_id'])) return ['code' => 0, 'msg' => $res['err_code_des']];

        $profit_share_log->save(['order_id' => $res['order_id']]);

        $order_info->save([
            'is_send_settlement_money' => 1, // 已结算
            'profit_sharing_status' => 1, // 已分账
            'settlement_amount' => $amount, // 分账金额

        ]);
        return ['code' => 1, 'msg' => '分账成功'];
    }

}
